if SERVER then

/* Save player info */
function SavePlayerInfo( ply )

	/* Debug output */
	DEBUG:Msg( "Saving " .. ply:Nick() .. "'s data", "SavePlayerInfo" )

	/* If the player instance doesn't have info, load / create it */
	if not ply.LastJoin or type( ply.LastJoin ) != "number" then
		
		/* Debug output */
		DEBUG:Msg( ply:Nick() .. "'s player info not found. Loading", "SavePlayerInfo" )
		
		/* Load player info */
		LoadPlayerInfo( ply )
	end
	
	/* Variables */
	local steamID		= SQLStr( ply:SteamID() )
	local firstJoin		= tostring( ply.FirstJoin )
	local lastJoin		= tostring( ply.LastJoin )
	local money			= tostring( ply.Money )
	
	/* Prepare the query */
	local query			= "UPDATE PlayerInfo SET FirstJoin = " .. firstJoin .. ", LastJoin = " .. lastJoin .. ", Money = " .. money
	query = query		.." WHERE SteamID = " .. steamID
	
	/* Execute the query */
	local result		= sql.Query( query )
	
	/* Debug output */
	if IsSQLError( result ) then
		DEBUG:Msg( ply:Nick() .. "'s player info could not be saved: " .. tostring( sql.LastError() ), "SavePlayerInfo" )
	else
		DEBUG:Msg( ply:Nick() .. "'s player info was successfully saved", "SavePlayerInfo" )
	end
	
	/* Return the result */
	return result
end

/* Save team info */
function SaveTeamInfo( teamObj )

	/* Ensure team is valid */
	local tm				= team.GetInfo( teamObj )
	if not tm then
		DEBUG:Msg( "Team not found: " .. tostring( teamObj ), "SaveTeamInfo" )
		return false
	end
	
	/* Variables */
	local id			= tostring( tm.ID )
	local name			= SQLStr( tostring( tm.Name ) )
	local color			= SQLStr( table.ToString( tm.Color ) )
	local maxPercent	= tostring( tm.MaxPercent )
	local chatName		= SQLStr( tostring( tm.ChatName ) )
	local createTime	= tostring( os.time() )
	
	/* Prepare the query */
	local query		= "UPDATE TeamInfo SET Name = " .. name .. ", Color = " .. color .. ", MaxPercent = " .. maxPercent .. ", ChatName = " .. chatName
	query = query .. " WHERE ID = " .. id
	
	/* Execute the query */
	local result		= sql.Query( query )
	
	/* Debug output */
	if IsSQLError( result ) then
		DEBUG:Msg( "Team info could not be saved for team " .. tostring( tm.ChatName ) .. ": " .. tostring( sql.LastError() ), "SaveTeamInfo" )
	else
		DEBUG:Msg( "Team info was successfully saved for team " .. tostring( tm.ChatName ), "SaveTeamInfo" )
	end
	
	/* Return the result */
	return result
end

/* Save all teams info */
function SaveTeamsInfo()
	for id,tm in pairs( team.GetGameTeams() ) do
		SaveTeamInfo( tm.ID )
	end
end

end